#pragma once
#include <Arduino.h>
#include "planner/planner.h"

#define SAVE_INT32_1 0x80000000U

typedef struct Touch_axis
{
  int32_t x, y;
} xy_axis;

typedef struct Touch_sensitivity
{
  int8_t sst[12];
} touch_s;

class Sensor
{
public:
  static xy_axis touch_bar[STORAGE];

  static int32_t mai_map[TOUCH_NUM][2]; // serial点位映射

  static uint8_t tsm12mc_read(uint8_t id, uint32_t *read); // TSM12MC读取

  static void sensor_bus_init(); // TSM12MC初始化

  static void tsm12_refence(uint8_t addr, uint16_t map); // 开关TSM12MC自校正

  static void touch_refence_update(uint32_t lock, bool reset = false); // 更新TSM12MC自校正

  static void tsm12mc_reset(); // 重置TSM12

  static void start_sample();  // 开始采样

  static uint8_t i2c_scan(); // 扫描I2C设备

  static touch_s touch_SPL[2]; // 灵敏度

  static void tsm12mc_settings_update(uint8_t addr);

  static void touch_spl_set(uint8_t id, int8_t target);

  static void touch_pressure_set(uint8_t id, int8_t target);

  static int8_t touch_spl_read(uint8_t id);

  static int8_t touch_pressure_read(uint8_t id);

  static void nvs_touch_spl_set(uint8_t id, int8_t target);

  static int8_t nvs_touch_spl_read(uint8_t id);

  static void clean_mai_map();

  static int8_t sample_time;

  static void set_sample_time(uint8_t time);

  static uint32_t touch_refence_map; 

  static uint32_t _old_touch_refence_map;

  static uint32_t touch_refence_lock;

  inline static uint8_t IRAM_ATTR check_down(uint32_t sensor, uint8_t id)
  {
    return !(sensor & 0b1 << id);
  }
  // inline static void test_gpio()
  // {
  //   // GPIO TEST
  //   for (uint8_t i = 0; i < (planner.get_gpio_num()); i++)
  //   {
  //     planner.set_GPIO(planner.sensor_gpio[i], 0);
  //     vTaskDelay(5);
  //   }
  //   vTaskDelay(50);
  //   for (uint8_t i = 0; i < (planner.get_gpio_num()); i++)
  //   {
  //     planner.set_GPIO(planner.sensor_gpio[i], 1);
  //     vTaskDelay(5);
  //   }
  // }
  inline static void test_led()
  {
    // LED TEST
    for (uint8_t i = 0; i < BUTTON_NUM; i++)
    {
      planner.set_GPIO(planner.sensor_gpio[i], 0);
      vTaskDelay(25);
    }
    vTaskDelay(100);
    for (uint8_t i = 0; i < BUTTON_NUM; i++)
    {
      planner.set_GPIO(planner.sensor_gpio[i], 1);
      vTaskDelay(25);
    }
  }
  inline static void settings_led(uint8_t mode)
  {
    planner.set_GPIO(planner.sensor_gpio[14], mode);
  }

private:
  static bool touch_wire_init;
};
extern Sensor sensor;